using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System;
using System.IO;

namespace DotNetNuke.Modules.DNNWeather
{
    /// <summary>
    /// The View class displays the content
    ///
    /// Typically your view control would be used to display content or functionality in your module.
    ///
    /// View may be the only control you have in your project depending on the complexity of your module
    ///
    /// Because the control inherits from DNNWeatherModuleBase you have access to any custom
    /// properties defined there, as well as properties from DNN such as PortalId, ModuleId, TabId,
    /// UserId and many more.
    /// </summary>
    public partial class View : DNNWeatherModuleBase//, IActionable
    {
        private const string TemplateDefault = "TemplateDefault.htm";
        private const string TemplateComplete = "TemplateComplete.htm";
        private const string CssDisplay = "display";
        private const string CssDisplay_None = "none";
        private const string Css_Display_Visible = "visible";
        private const string UserControlName = "View.ascx";

        private const string STR_CityId = "CityId";
        private const string STR_CityName = "CityName";
        private const string STR_Template = "Template";
        private const string STR_DegreesUnits = "DegreesUnits";

        #region "Properties"

        /// <summary>
        /// Property used for the city being shown
        /// </summary>
        public string CityId
        {
            get
            {
                if (ViewState[STR_CityId] == null ||
                    ViewState[STR_CityId].ToString().Equals(string.Empty))
                {
                    if (Settings.Contains(DNNWeather.Settings.Key_CityId) && Settings.Contains(DNNWeather.Settings.Key_CityName) &&
                        !string.IsNullOrWhiteSpace(Settings[DNNWeather.Settings.Key_CityId].ToString()))
                    {
                        return Settings[DNNWeather.Settings.Key_CityId].ToString();
                    }
                    return null;
                }
                else
                {
                    return ViewState[STR_CityId].ToString();
                }
            }
            set
            {
                ViewState[STR_CityId] = value;
            }
        }

        /// <summary>
        /// Property used for the city name being shown
        /// </summary>
        public string CityName
        {
            get
            {
                if (!string.IsNullOrEmpty(CityId))
                {
                    if (ViewState[STR_CityName] == null ||
                        ViewState[STR_CityName].ToString().Equals(string.Empty))
                    {
                        if (Settings.Contains(DNNWeather.Settings.Key_AlternativeCityName) || Settings.Contains(DNNWeather.Settings.Key_CityName))
                        {
                            string cityName = Settings.Contains(DNNWeather.Settings.Key_AlternativeCityName) &&
                            !string.IsNullOrWhiteSpace(Settings[DNNWeather.Settings.Key_AlternativeCityName].ToString()) ?
                                Settings[DNNWeather.Settings.Key_AlternativeCityName].ToString() :
                                Settings[DNNWeather.Settings.Key_CityName].ToString();
                            return Localization.GetString("CityName", Localization.GetResourceFile(this, UserControlName)).Replace("[CITYNAME]", cityName);
                        }
                    }
                    else
                    {
                        return Localization.GetString("CityName", Localization.GetResourceFile(this, UserControlName)).Replace("[CITYNAME]", ViewState[STR_CityName].ToString()); ;
                    }
                }
                return string.Empty;
            }
            set
            {
                ViewState[STR_CityName] = value;
            }
        }

        /// <summary>
        /// Property used for the conditions
        /// </summary>
        public string Conditions
        {
            get
            {
                if (!string.IsNullOrEmpty(CityId))
                {
                    return
                        String.Format("'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}','{17}','{18}','{19}','{20}','{21}','{22}','{23}','{24}','{25}','{26}','{27}','{28}','{29}','{30}','{31}','{32}','{33}','{34}','{35}','{36}','{37}','{38}','{39}','{40}','{41}','{42}','{43}','{44}','{45}','{46}','{47}'",
                        Localization.GetString("Condition_tornado", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_tropicalStorm", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_hurricane", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_severeThunderstorms", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_thunderstorms", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_mixedRainAndSnow", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_mixedRainAndSleet", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_mixedSnowAndSleet", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_freezingDrizzle", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_drizzle", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_freezingRain", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_showers", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_showers1", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_snowFlurries", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_lightSnowShowers", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_blowingSnow", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_snow", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_hail", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_sleet", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_dust", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_foggy", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_haze", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_smoky", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_blustery", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_windy", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_cold", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_cloudy", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_mostlyCloudyNight", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_mostlyCloudyDay", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_partlyCloudyNight", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_partlyCloudyDay", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_clearNight", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_sunny", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_fairNight", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_fairDay", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_mixedRainAndHail", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_hot", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_isolatedThunderstorms", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_scatteredThunderstorms", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_scatteredThunderstorms1", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_scatteredShowers", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_heavySnow", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_scatteredSnowShowers", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_heavySnow1", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_partlyCloudy", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_thundershowers", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_snowShowers", Localization.GetResourceFile(this, UserControlName)),
                        Localization.GetString("Condition_isolatedThundershowers", Localization.GetResourceFile(this, UserControlName)));
                }
                return string.Empty;
            }
        }

        /// <summary>
        /// Property used for the condition image path
        /// </summary>
        public string ConditionImagePath
        {
            get
            {
                if (!string.IsNullOrEmpty(CityId))
                {
                    return ControlPath.Replace(@"\", "/") + "Files/Images/[Id].png";
                }
                return string.Empty;
            }
        }

        /// <summary>
        /// Property used for the weather template
        /// </summary>
        public string Template
        {
            get
            {
                string templateFilePath = string.Empty;
                if (ViewState[STR_Template] == null ||
                    ViewState[STR_Template].ToString().Equals(string.Empty))
                {
                    //default template
                    DNNWeather.Settings.WeatherTemplate template = DNNWeather.Settings.WeatherTemplate.Default;

                    //if the user has a selection, get it
                    if (Settings.Contains(DNNWeather.Settings.Key_TemplateId))
                    {
                        if (!Enum.TryParse<DNNWeather.Settings.WeatherTemplate>(Settings[DNNWeather.Settings.Key_TemplateId].ToString(), out template))
                        {
                            template = DNNWeather.Settings.WeatherTemplate.Custom;
                        }
                    }

                    string templateDocument = string.Empty;
                    switch (template)
                    {
                        case DNNWeather.Settings.WeatherTemplate.Custom:
                            string templateFile = string.Empty;
                            if (Settings.Contains(DNNWeather.Settings.Key_TemplateCustomFile) &&
                                Settings[DNNWeather.Settings.Key_TemplateCustomFile].ToString() != string.Empty)
                            {
                                templateFile = Settings[DNNWeather.Settings.Key_TemplateCustomFile].ToString();
                            }
                            else
                            {
                                templateFile = TemplateComplete;
                            }
                            templateDocument = @"Custom\" + templateFile;
                            break;

                        default:
                            templateDocument = TemplateDefault;
                            break;
                    }
                    templateFilePath = Server.MapPath(String.Format(@"{0}\Files\Templates\{1}", ControlPath, templateDocument));
                }
                else
                {
                    templateFilePath = Server.MapPath(String.Format(@"{0}\{1}", ControlPath, ViewState[STR_Template].ToString()));
                }

                if (File.Exists(templateFilePath))
                    return File.ReadAllText(templateFilePath);
                //return default template
                return File.ReadAllText(Server.MapPath(String.Format(@"{0}\Files\Templates\{1}", ControlPath, TemplateDefault)));
            }
            set
            {
                ViewState[STR_Template] = value;
            }
        }

        /// <summary>
        /// Property used for the degrees units
        /// </summary>
        public string DegreeUnits
        {
            get
            {
                if (ViewState[STR_DegreesUnits] == null ||
                    ViewState[STR_DegreesUnits].ToString().Equals(string.Empty))
                {
                    //default degree unit
                    DNNWeather.Settings.DegreesUnits degreesUnit = DNNWeather.Settings.DegreesUnits.c;

                    //if the user has a selection, get it
                    if (Settings.Contains(DNNWeather.Settings.Key_DegreesUnits))
                    {
                        Enum.TryParse<DNNWeather.Settings.DegreesUnits>(Settings[DNNWeather.Settings.Key_DegreesUnits].ToString(), out degreesUnit);
                    }

                    return degreesUnit.ToString();
                }
                else
                {
                    return ViewState[STR_DegreesUnits].ToString();
                }
            }
            set
            {
                ViewState[STR_DegreesUnits] = value;
            }
        }

        #endregion "Properties"

        #region Event Handlers

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">
        /// An <see cref="T:System.EventArgs" /> object that contains the event data.
        /// </param>
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.Page_Load);
        }

        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    if (string.IsNullOrEmpty(CityId))
                    {
                        ClearMessages();

                        //Show Warning
                        if (IsEditable)
                            ShowMessage(Localization.GetString("InfoModuleNotConfigured", Localization.GetResourceFile(this, UserControlName)), MessageClass_Warning);
                    }
                    else
                    {
                        lt_weatherTemplate.Text = Template;
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        #endregion Event Handlers

        #region Optional Interfaces

        //public ModuleActionCollection ModuleActions
        //{
        //    get
        //    {
        //        ModuleActionCollection Actions = new ModuleActionCollection();
        //        Actions.Add(GetNextActionID(), Localization.GetString("EditModule", Localization.GetResourceFile(this, UserControlName)), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false);
        //        return Actions;
        //    }
        //}

        #endregion Optional Interfaces

        #region "Aux Functions"

        /// <summary>
        /// Clears message labels, for warning and errors
        /// </summary>
        public void ClearMessages()
        {
            ShowMessage(string.Empty, string.Empty);
        }

        /// <summary>
        /// Presents a message to the user
        /// </summary>
        /// <param name="message">the message to show</param>
        /// <param name="messageTypeClass">the type of message class</param>
        private void ShowMessage(string message, string messageTypeClass)
        {
            pnl_message.Style.Clear();
            pnl_message.CssClass = messageTypeClass;
            pnl_message.Style.Add(CssDisplay, string.IsNullOrEmpty(message) ? CssDisplay_None : Css_Display_Visible);
            lt_message.Text = message;
        }

        #endregion "Aux Functions"
    }
}